#!/bin/bash
# -*- coding: utf-8 -*-
"""
@file install_dependencies.sh
@brief 依赖安装脚本
@details 检查并安装运行无刷电机驱动器控制器所需的所有依赖
@author zhang33
@date 2025-09-05
"""

set -e  # 遇到错误立即退出

echo "=========================================="
echo "无刷电机驱动器控制器 - 依赖安装脚本"
echo "作者: zhang33"
echo "日期: 2025-09-05"
echo "=========================================="
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -eq 0 ]]; then
        log_warning "检测到root用户，建议使用普通用户运行此脚本"
        read -p "是否继续？(y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "安装已取消"
            exit 1
        fi
    fi
}

# 检测操作系统
detect_os() {
    log_info "检测操作系统..."
    
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS=$NAME
        VERSION=$VERSION_ID
        log_info "检测到操作系统: $OS $VERSION"
    else
        log_error "无法检测操作系统"
        exit 1
    fi
    
    # 设置包管理器
    if command -v apt-get &> /dev/null; then
        PACKAGE_MANAGER="apt"
        UPDATE_CMD="sudo apt update"
        INSTALL_CMD="sudo apt install -y"
    elif command -v yum &> /dev/null; then
        PACKAGE_MANAGER="yum"
        UPDATE_CMD="sudo yum update -y"
        INSTALL_CMD="sudo yum install -y"
    elif command -v dnf &> /dev/null; then
        PACKAGE_MANAGER="dnf"
        UPDATE_CMD="sudo dnf update -y"
        INSTALL_CMD="sudo dnf install -y"
    elif command -v pacman &> /dev/null; then
        PACKAGE_MANAGER="pacman"
        UPDATE_CMD="sudo pacman -Sy"
        INSTALL_CMD="sudo pacman -S --noconfirm"
    else
        log_error "不支持的包管理器"
        exit 1
    fi
    
    log_info "使用包管理器: $PACKAGE_MANAGER"
}

# 检查Python版本
check_python() {
    log_info "检查Python版本..."
    
    if command -v python3 &> /dev/null; then
        PYTHON_VERSION=$(python3 --version 2>&1 | cut -d' ' -f2)
        log_info "检测到Python版本: $PYTHON_VERSION"
        
        # 检查版本是否满足要求 (>= 3.8)
        PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d'.' -f1)
        PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d'.' -f2)
        
        if [[ $PYTHON_MAJOR -eq 3 && $PYTHON_MINOR -ge 8 ]]; then
            log_success "Python版本满足要求 (>= 3.8)"
        else
            log_error "Python版本不满足要求，需要 >= 3.8，当前版本: $PYTHON_VERSION"
            exit 1
        fi
    else
        log_error "未检测到Python3，请先安装Python 3.8+"
        exit 1
    fi
}

# 检查pip
check_pip() {
    log_info "检查pip..."
    
    if command -v pip3 &> /dev/null; then
        PIP_VERSION=$(pip3 --version 2>&1 | cut -d' ' -f2)
        log_success "检测到pip版本: $PIP_VERSION"
    else
        log_warning "未检测到pip3，正在安装..."
        install_pip
    fi
}

# 安装pip
install_pip() {
    log_info "安装pip..."
    
    if [[ $PACKAGE_MANAGER == "apt" ]]; then
        $INSTALL_CMD python3-pip
    elif [[ $PACKAGE_MANAGER == "yum" || $PACKAGE_MANAGER == "dnf" ]]; then
        $INSTALL_CMD python3-pip
    elif [[ $PACKAGE_MANAGER == "pacman" ]]; then
        $INSTALL_CMD python-pip
    fi
    
    if command -v pip3 &> /dev/null; then
        log_success "pip安装成功"
    else
        log_error "pip安装失败"
        exit 1
    fi
}

# 安装系统依赖
install_system_dependencies() {
    log_info "安装系统依赖..."
    
    # 更新包列表
    log_info "更新包列表..."
    $UPDATE_CMD
    
    # 根据操作系统安装不同的依赖
    if [[ $PACKAGE_MANAGER == "apt" ]]; then
        # Ubuntu/Debian
        log_info "安装Ubuntu/Debian系统依赖..."
        $INSTALL_CMD \
            python3-tk \
            python3-dev \
            build-essential \
            libffi-dev \
            libssl-dev \
            pkg-config \
            libusb-1.0-0-dev \
            libudev-dev
    elif [[ $PACKAGE_MANAGER == "yum" || $PACKAGE_MANAGER == "dnf" ]]; then
        # CentOS/RHEL/Fedora
        log_info "安装CentOS/RHEL/Fedora系统依赖..."
        $INSTALL_CMD \
            tkinter \
            python3-devel \
            gcc \
            gcc-c++ \
            make \
            libffi-devel \
            openssl-devel \
            pkgconfig \
            libusb1-devel \
            systemd-devel
    elif [[ $PACKAGE_MANAGER == "pacman" ]]; then
        # Arch Linux
        log_info "安装Arch Linux系统依赖..."
        $INSTALL_CMD \
            tk \
            python \
            base-devel \
            libffi \
            openssl \
            pkgconf \
            libusb \
            systemd
    fi
    
    log_success "系统依赖安装完成"
}

# 安装Python依赖
install_python_dependencies() {
    log_info "安装Python依赖..."
    
    if [[ -f "requirements.txt" ]]; then
        log_info "从requirements.txt安装Python包..."
        pip3 install -r requirements.txt
        log_success "Python依赖安装完成"
    else
        log_warning "未找到requirements.txt文件，手动安装核心依赖..."
        pip3 install \
            pyserial>=3.4 \
            pymodbus>=2.5.3 \
            keyboard>=0.13.5 \
            flask>=2.0.0 \
            flask-cors>=3.0.0
        log_success "核心Python依赖安装完成"
    fi
}

# 验证安装
verify_installation() {
    log_info "验证安装..."
    
    # 检查Python包
    local packages=("pymodbus" "serial" "flask" "flask_cors")
    local missing_packages=()
    
    for package in "${packages[@]}"; do
        if python3 -c "import $package" 2>/dev/null; then
            log_success "✓ $package 可用"
        else
            log_error "✗ $package 不可用"
            missing_packages+=("$package")
        fi
    done
    
    # 检查tkinter
    if python3 -c "import tkinter" 2>/dev/null; then
        log_success "✓ tkinter 可用"
    else
        log_error "✗ tkinter 不可用"
        missing_packages+=("tkinter")
    fi
    
    # 检查keyboard包（需要特殊处理）
    if python3 -c "import keyboard" 2>/dev/null; then
        log_success "✓ keyboard 可用"
    else
        log_warning "✗ keyboard 不可用（可能需要root权限）"
    fi
    
    if [[ ${#missing_packages[@]} -eq 0 ]]; then
        log_success "所有依赖安装成功！"
        return 0
    else
        log_error "以下包安装失败: ${missing_packages[*]}"
        return 1
    fi
}

# 创建虚拟环境（可选）
create_virtual_env() {
    log_info "是否创建Python虚拟环境？"
    read -p "创建虚拟环境可以避免包冲突 (y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "创建虚拟环境..."
        
        if command -v python3 -m venv &> /dev/null; then
            python3 -m venv venv
            log_success "虚拟环境创建成功"
            
            log_info "激活虚拟环境..."
            source venv/bin/activate
            
            log_info "在虚拟环境中安装依赖..."
            pip install --upgrade pip
            pip install -r requirements.txt
            
            log_success "虚拟环境设置完成"
            log_info "使用方法: source venv/bin/activate"
        else
            log_error "无法创建虚拟环境，请手动安装python3-venv"
        fi
    fi
}

# 显示使用说明
show_usage() {
    echo ""
    echo "=========================================="
    echo "安装完成！"
    echo "=========================================="
    echo ""
    echo "使用方法:"
    echo "1. GUI模式:"
    echo "   ./start_gui.sh"
    echo "   或 python3 start.py gui"
    echo ""
    echo "2. API服务器模式:"
    echo "   ./start_api.sh"
    echo "   或 python3 start.py api"
    echo ""
    echo "3. 查看文档:"
    echo "   cat doc/README.md"
    echo ""
    echo "注意事项:"
    echo "- 首次使用前请确保硬件连接正确"
    echo "- 需要执行相序学习"
    echo "- 建议先查看用户使用指南"
    echo ""
}

# 主函数
main() {
    log_info "开始安装依赖..."
    
    # 检查root用户
    check_root
    
    # 检测操作系统
    detect_os
    
    # 检查Python
    check_python
    
    # 检查pip
    check_pip
    
    # 安装系统依赖
    install_system_dependencies
    
    # 安装Python依赖
    install_python_dependencies
    
    # 验证安装
    if verify_installation; then
        # 创建虚拟环境（可选）
        create_virtual_env
        
        # 显示使用说明
        show_usage
        
        log_success "依赖安装完成！"
        exit 0
    else
        log_error "依赖安装失败，请检查错误信息"
        exit 1
    fi
}

# 错误处理
trap 'log_error "安装过程中发生错误，退出码: $?"' ERR

# 运行主函数
main "$@"
